package com.lngsyz.ywtb.wx.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.http.client.ResponseHandler;
import org.apache.http.impl.client.BasicResponseHandler;

import com.lngsyz.ywtb.util.CommonUtil;
import com.lngsyz.ywtb.util.HttpUtils;
import com.lngsyz.ywtb.wx.entity.WxSignature;

import net.sf.json.JSONObject;

public class GetWxSignatureUtil {

	// 网页授权接口
	public final static String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
	// 网页授权接口
	public final static String GET_JSAPI_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";

	public static WxSignature getSignature(String url) {
		String _appId = "wx0e37e065d64f033c";
    	String _appSecret = "7002776cb679eb221172412f8a1d8a87";
		// TODO Auto-generated method stub
		String noncestr = UUID.randomUUID().toString().replaceAll("-", "");//随机字符串
		String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳 到秒
		//第一步:获取access_token(需要在服务器上 )
		Map<String, String> tokenMap = getAccessToken(_appId, _appSecret);
		String accessToken = tokenMap.containsKey("accessToken") ? tokenMap.get("accessToken") : "";
		//第二步:获取jsapi_ticket
		Map<String, String> jsapiTicket = jsapiTicket(accessToken);
		String ticket = jsapiTicket.containsKey("ticket") ? jsapiTicket.get("ticket") : "";
		//第三步:用时间戳、随机数、jsapi_ticket和要访问的url按照签名算法拼接字符串
		//4获取url
		//根据项目需要获取对应的url地址
		//5、将参数排序并拼接字符串
		String str = "jsapi_ticket="+ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;
		//6、将字符串进行sha1加密
		String signature = sha1(str);
		WxSignature ws = new WxSignature();
		ws.setAppId(_appId);
		ws.setTimestamp(timestamp);
		ws.setTicket(ticket);
		ws.setAccessToken(accessToken);
		ws.setNoncestr(noncestr);
		ws.setSignature(signature);
		return ws;
	}
	
	public static String sha1(String input) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
            byte[] inputBytes = input.getBytes();
            byte[] digestBytes = messageDigest.digest(inputBytes);
            StringBuilder stringBuilder = new StringBuilder();
            for (byte b : digestBytes) {
                stringBuilder.append(String.format("%02x", b));
            }
            return stringBuilder.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static Map<String, String> getAccessToken(String appid, String appsecret) {
        String requestUrl = GET_TOKEN_URL.replace("APPID", appid).replace("SECRET", appsecret);
        Map<String, String> result = new HashMap<String, String>();
        String accessToken = null;
        try {
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = HttpUtils.doGet(requestUrl, responseHandler);
            JSONObject OpenidJSON = JSONObject.fromObject(response);
            accessToken = String.valueOf(OpenidJSON.get("access_token"));
            result.put("accessToken", accessToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    

    public static Map<String, String> jsapiTicket(String accessToken) {
        String requestUrl = GET_JSAPI_URL.replace("ACCESS_TOKEN", accessToken);
        Map<String, String> result = new HashMap<String, String>();
        try {
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = HttpUtils.doGet(requestUrl, responseHandler);
            JSONObject openidJSON = JSONObject.fromObject(response);
            String errcode = String.valueOf(openidJSON.get("errcode"));
            String errmsg = String.valueOf(openidJSON.get("errmsg"));
            String ticket = String.valueOf(openidJSON.get("ticket"));
            String expires_in = String.valueOf(openidJSON.get("expires_in"));
            result.put("errcode", errcode);
            result.put("errmsg", errmsg);
            result.put("ticket", ticket);
            result.put("expires_in", expires_in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    public static void main(String[] args) {
    	
    	WxSignature rtn = GetWxSignatureUtil.getSignature("http://120.201.201.212:60011/");
    	System.out.print(JSONObject.fromObject(rtn));
    }
}
